package org.example.demo21.controller;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.example.demo21.entity.bo.DemoBO;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@Tag(name = "测试接口")
@RequestMapping("/eai/test")
@Slf4j
public class TestController {

    public static List<DemoBO> entitiesList;

    static {
        entitiesList = new ArrayList<>();
        entitiesList.add(new DemoBO().setId(1L).setAge(20).setName("Ares"));
        entitiesList.add(new DemoBO().setId(2L).setAge(21).setName("Zeus"));
        entitiesList.add(new DemoBO().setId(3L).setAge(22).setName("Poseidon"));
    }

    @PostMapping(value = "/add")
    @Operation(summary = "新增", description = "新增", method = "POST")
    public HashMap<String, Object> add(DemoBO demoBO) {
        entitiesList.add(demoBO.setId(IdWorker.getId()));
        log.info("添加成功：{}" , demoBO);
        HashMap<String, Object> result = new HashMap<>();
        result.put("ret",0);
        result.put("data",demoBO);
        return result;
    }

    @GetMapping("/list")
    @Operation(summary = "查询列表", description = "查询列表", method = "GET")
    public  Map<String,Object> list(){
        Map<String, Object> result = new HashMap<>();
        result.put("ret",0);
        result.put("data",entitiesList);
        return result;
    }


    @PutMapping("/update")
    @Operation(summary = "更新", description = "更新", method = "PUT")
    public Map<String,Object> update(DemoBO demoBO) {
        entitiesList.remove(entitiesList.stream().filter(item -> item.getId().equals(demoBO.getId())).findAny().get());
        entitiesList.add(demoBO);
        log.info("修改成功：{}", demoBO);
        Map<String, Object> result = new HashMap<>();
        result.put("ret",0);
        result.put("data",demoBO);
        return result;
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除", description = "删除", method = "DELETE")
    public Map<String, Object> delete(@PathVariable("id") Long id) {
        Optional<DemoBO> any = entitiesList.stream().filter(item -> item.getId().equals(id)).findAny();
        any.ifPresent(demoBO -> entitiesList.remove(demoBO));
        log.info("删除成功！");
        Map<String, Object> result = new HashMap<>();
        result.put("ret",0);
        result.put("data",id);
        return result;
    }

}
